// 防止变量提升，计算房间类型和房间数组
$(function() {
    var roomList = $('#roomList');
    var roomItem = roomList.find('.roomItem');
    var datePicker = $('#datePicker');
    var roomTypes = [];
    window.roomTypeData = {};
    window.roomItemType = {};
    window.startDate = datePicker.data('start');
    var tmpRoomItem, tmpRoomType;
    for (var i = 0; i < roomItem.length; i++) {
        tmpRoomItem = {};
        tmpRoomItem.value = roomItem.eq(i).data('room');
        tmpRoomItem.name = roomItem.eq(i).data('name');
        tmpRoomItem.from = roomItem.eq(i).data('from');
        tmpRoomType = {};
        tmpRoomType.value = roomItem.eq(i).data('type-value');
        tmpRoomType.price = roomItem.eq(i).data('price');
        tmpRoomItem.price = tmpRoomType.price;
        tmpRoomItem.type = tmpRoomType.value;
        if ($.inArray(tmpRoomType.value, roomTypes) === -1) {
            tmpRoomType.name = roomItem.eq(i).data('type');
            window.roomTypeData[tmpRoomType.value] = tmpRoomType;
            window.roomTypeData[tmpRoomType.value].rooms = [];
            window.roomTypeData[tmpRoomType.value].roomIds = [];
            roomTypes.push(tmpRoomType.value);
        }
        window.roomTypeData[tmpRoomType.value].rooms.push(tmpRoomItem);
        window.roomTypeData[tmpRoomType.value].roomIds.push(tmpRoomItem.value);
        window.roomItemType[tmpRoomItem.value] = tmpRoomItem;
    }

    var transformOrderInfo = function(startDate, orderList) {
        var showDate = [];
        var i;
        for (i = 0; i < 31; i++) {
            showDate.push(startDate.customDays(i).customFormat());
        }
        for (i = 0; i < orderList.length; i++) {
            // 订单是在选中开始日期之前的时候
            if ($.inArray(orderList[i].start, showDate) === -1) {
                orderList[i].startRender = showDate[0];
                orderList[i].nightRender = parseInt(orderList[i].night) + getDate(orderList[i].start).getDays(startDate);
            } else {
                orderList[i].startRender = orderList[i].start;
                orderList[i].nightRender = parseInt(orderList[i].night);
            }
        }
        return orderList;
    };
    // 对于动态添加的项显示tooltip
    $('body').delegate('[data-toggle="tooltip"]', 'mouseover', function() {
        $(this).tooltip('show');
    });
    $('#orderArea').on('scroll', function() {
        var top = $(this).scrollTop();
        var left = $(this).scrollLeft();
        $('#calendarScrollContainer').scrollTop(top);
        $('#roomTypeContainer').scrollLeft(left);
    });
    datePicker.on('click', function(e) {
        $('#datePickerInput').datepicker('show');
    });
    $('#datePickerInput').datepicker({
        format: 'yyyy-mm-dd',
        startDate: '2000-01-01',
        endDate: '2037-12-01',
        language: 'zh-CN',
        orientation: 'top left',
        autoclose: true,
        todayHighlight: true
    }).on('changeDate', function(e) {
        var selectedDate = e.date;
        refreshSelectedDate(selectedDate);
    });
    // 上一个时期
    $('#datePickerLast').on('click', function(e) {
        var originalStart = window.startDate;
        var originalStartDate = getDate(originalStart);
        var selectedDate = originalStartDate.customDays(-31);
        $('#datePickerInput').datepicker('setDate', selectedDate);
    });
    // 下一个时期
    $('#datePickerNext').on('click', function(e) {
        var originalStart = window.startDate;
        var originalStartDate = getDate(originalStart);
        var selectedDate = originalStartDate.customDays(31);
        $('#datePickerInput').datepicker('setDate', selectedDate);
    });
    // 可通过添加或删除orderList来重新调用该方法，刷新页面
    $('#doc').on('refresh.meizhu', function() {
        var startDate = getDate($('#datePicker').data('start'));
        var orderList = window.orderList;
        orderList = transformOrderInfo(startDate, orderList);
        window.orderList = orderList;
        var roomDateOrder = {};
        var roomHourDateOrder = {};
        $.each(window.roomItemType, function(roomId, room) {
            roomDateOrder[roomId] = {};
            roomHourDateOrder[roomId] = {};
        });
        var typeDateCount = {};
        var serviceroomId = [];
        $.each(window.roomTypeData, function(roomTypeId, roomType) {
            typeDateCount[roomTypeId] = {};
            // 初始化房型剩余量
            var typeCount = roomType.roomIds.length;
            serviceroomId = serviceroomId.concat(roomType.roomIds);
            for (var i = 0; i < 31; i++) {
                typeDateCount[roomTypeId][startDate.customDays(i).customFormat()] = typeCount;
            }
        });
        var dateRoomAvaliable = {};
        var calendarHashSkipRender = {};
        var roomCount = $('#roomList').data('rooms');
        var calendarHash = '';
        for (var i = 0; i < 31; i++) {
            var timestamp = Date.parse(startDate.customDays(i))/ 1000;
            var num = 0;
            for(var j=0;j<serviceroomId.length;j++){
                if(window.roomservice[serviceroomId[j]+'_'+timestamp] == 1){
                    num++;
                }
            }
            calendarHash = startDate.customDays(i).customFormat();
            dateRoomAvaliable[calendarHash] = parseInt(roomCount)-parseInt(num);
            calendarHashSkipRender[calendarHash] = {};
        }
        // 记录不用画td的位置
        var tempRoomId = [];
        var tempCurrentDateFormat = [];
        $.each(orderList, function(key, orderItem) {
            var isaddHour = false;
            var addId = true;
            var currentDateFormat = orderItem.startRender;
            var currentDate = getDate(currentDateFormat);
            var roomId = orderItem.room;
            var roomType = window.roomItemType[roomId].type;
            var orderItemNightRender = parseInt(orderItem.nightRender);
            var orderArr = [];
            if(orderItem.hour>0){
                var isRepeat = false;
                if(tempRoomId.length>0){
                    for(var i=0;i<tempRoomId.length;i++){
                        if(tempRoomId[i] == roomId && tempCurrentDateFormat[i] == currentDateFormat){
                            if(roomHourDateOrder[roomId][currentDateFormat].hourList != undefined){
                                roomHourDateOrder[roomId][currentDateFormat].hourList.push(orderItem);
                            }else{
                                orderArr.push(orderItem);
                            }
                            isRepeat = true;
                            if(orderItem.status == lang('status.reserve') || orderItem.status == lang('status.checkIn')|| orderItem.status == lang('status.needOut')){
                                isaddHour = true;
                            }
                        }       
                    }                
                }    
                if(orderItem.status == lang('status.reserve') || orderItem.status == lang('status.checkIn')|| orderItem.status == lang('status.needOut')){
                    isaddHour = true;
                }
                if(isRepeat){
                    if(roomHourDateOrder[roomId][currentDateFormat].hourList == undefined){
                        roomHourDateOrder[roomId][currentDateFormat].hourList =  orderArr;
                    }
                }else{
                    roomHourDateOrder[roomId][currentDateFormat] = orderItem;
                    
                }                   
                if(tempRoomId.length>0){
                    for(var i=0;i<tempRoomId.length;i++){
                        if(tempRoomId[i] == roomId && tempCurrentDateFormat[i] == currentDateFormat){addId = false;}
                    }
                    if(addId){
                        tempRoomId.push(roomId);
                        tempCurrentDateFormat.push(currentDateFormat);
                    }
                }else{
                    tempRoomId.push(roomId);
                    tempCurrentDateFormat.push(currentDateFormat);
                }
            }else{
                roomDateOrder[roomId][currentDateFormat] = orderItem;
            }       
            if(isaddHour){
                orderItemNightRender++;
            }
            // 房型剩余量减少一
            var changeDateFormat;
            for (var i = 0; i < orderItemNightRender; i++) {
                changeDateFormat = currentDate.customDays(i).customFormat();
                typeDateCount[roomType][changeDateFormat]--;
                dateRoomAvaliable[changeDateFormat]--;
//              if (i > 0) {
//                  calendarHashSkipRender[changeDateFormat][roomId] = 1;
//              }
            }
        });
        var renderHtml = '';
        $('#orderListBody').html('');
        // 开始生成html，从房型开始
        var templateOriginal = $('#templateOrderItem');
        var templateTipOriginal = $('#templateOrderItemTip');
        // 循环到的天数间隔
        var dateIndex = 0;
        var currentDate, currentDateFormat;
        while (dateIndex < 31) {
            currentDate = startDate.customDays(dateIndex);
            currentDateFormat = currentDate.customFormat();
            renderHtml += '<tr class="calendarOrderTr" data-date="' + currentDateFormat + '">';
            $.each(window.roomTypeData, function(roomTypeId, roomType) {
                // 房间单元
                $.each(roomType.rooms, function(index, room) {
                    var roomId = room.value;
                    var template, orderInfo, orderItem, tooltipTemplate,orderHourItem,ordercomItem,orderHoursItem,orderHourInfo;
                    template = $(templateOriginal.clone().html());
                    template.attr('data-value', roomId);
                    template.attr('data-type-value', roomTypeId);
                    orderInfo = roomDateOrder[roomId][currentDateFormat];
                    orderHourInfo = roomHourDateOrder[roomId][currentDateFormat];
                    var hourRoom = 0;
                    if (orderInfo !== undefined) {
                        var endDate = datePicker.find('.year').text()+'/'+datePicker.find('.end').text();
                        var month = parseInt(Math.abs( getDate(endDate) - getDate(window.startDate) ) / 86400000)+1;
                        var differ_day = parseInt(Math.abs( getDate(endDate) - getDate(orderInfo.start) ) / 86400000)+1;                                           
                        var nightRender = orderInfo.nightRender;
                        if(differ_day>31){
                            if(nightRender>month){nightRender = month;}
                        }else{
                            if(nightRender>differ_day){nightRender = differ_day;}
                        }
                       // 存在订单
                       //template.attr('rowspan', orderInfo.nightRender);
                        orderItem = template.find('.order-item');
                        orderItem.css('height',nightRender*46);
                        orderItem.attr('data-value', orderInfo.id);
                        orderItem.attr('data-parent', orderInfo.order);
                        orderItem.attr('data-status', orderInfo.status);
                        template.find('.order-customer').html(orderInfo.name);
                        template.find('.order-channel').html(orderInfo.channelname);
                        if (orderInfo.receipt != orderInfo.pay) {
                            template.find('.order-icon').removeClass('hidden');
                        }
                        orderItem.removeClass('hidden');
                        // 订单的背景显示状态
                        if (orderInfo.status === lang('status.reserve') || orderInfo.status === lang('status.payment')) {
                            orderItem.addClass('status-not-in');
                        } else {
                            if (orderInfo.status === lang('status.checkIn')) {
                                orderItem.addClass('status-in');
                            } else if(orderInfo.status === lang('status.needOut')){
                                orderItem.addClass('status-need-out');
                            }  else {
                                orderItem.addClass('status-out');
                            }
                        }
                        if(orderInfo.status == lang('status.checkOut')){
                            var priceKey = room['value']+'_'+ parseInt((new Date(currentDateFormat.replace(new RegExp(/-/g),'/'))).getTime()/1000);
                            template.attr('data-date', currentDateFormat);
                            template.attr('data-hourprice', window.hourprice[priceKey]);
                            template.attr('data-hourpay', window.hourpay[priceKey]);
                            template.attr('data-longprice', window.longprice[priceKey]);
                            template.addClass('without-order');
                            orderItem.addClass('checkout');
                            gettooltipTemplate(orderInfo,template.find('.order-item-container'),1);
                        }else{
                            if(orderInfo.month>0){
                                gettooltipTemplate(orderInfo,orderItem,3);
                            }else{
                                gettooltipTemplate(orderInfo,orderItem,0);
                            }  
                        }             
                    } else {
                        // 不存在订单
                        template.attr('data-date', currentDateFormat);
                        template.addClass('without-order');
                        var priceKey = roomId+'_'+ parseInt((new Date(currentDateFormat.replace(new RegExp(/-/g),'/'))).getTime()/1000);
                        template.attr('data-hourprice', window.hourprice[priceKey]);
                        template.attr('data-hourpay', window.hourpay[priceKey]);
                        template.attr('data-longprice', window.longprice[priceKey]);
                        if(window.roomservice[priceKey] == '1'){
                            template.find('.maintain-icon').removeClass('hidden');
                            template.find('.order-hour-box').addClass('hidden');
                        }else{
                            template.find('.maintain-icon').addClass('hidden');
                        }                        
                    }
                    if(orderHourInfo !== undefined){
                        // 存在钟点房订单
                        hourRoom++;
                        orderHourItem = template.find('.order-hour');
                        if (orderHourInfo.receipt != orderHourInfo.pay) {
                            orderHourItem.find('.order-icon').removeClass('hidden');
                        }
                        orderHourItem.removeClass('hidden');
                        // 订单的背景显示状态
                        if (orderHourInfo.status === lang('status.reserve') || orderHourInfo.status === lang('status.payment')) {
                            orderHourItem.addClass('status-hour-not-in');
                        } else {
                            if (orderHourInfo.status === lang('status.checkIn')) {
                                orderHourItem.addClass('status-hour-in');
                            } else if(orderHourItem.status === lang('status.needOut')){
                                orderHourItem.addClass('status-hour-need-out');
                            }  else {
                                orderHourItem.addClass('status-hour-out');
                            }
                        }    
                        if(orderHourInfo.hourList){
                            gettooltipTemplate(orderHourInfo,template.find('.order-hour-container'),1);
                            var hourId = [];
                            var isTdRepeat = true;
                            for(var i=0 ;i< orderHourInfo.hourList.length;i++){
                                if(hourId.length>0){     
                                    for(var j=0 ;j< hourId.length;j++){
                                        if(hourId[j] == orderHourInfo.hourList[i].id){
                                            isTdRepeat = false;
                                        }
                                    }
                                }
                                if(isTdRepeat){
                                    hourId.push(orderHourInfo.hourList[i].id);
                                    hourRoom++;
                                    gettooltipTemplate(orderHourInfo.hourList[i],template.find('.order-hour-container'),1); 
                                }
                            }
                        }else{
                            gettooltipTemplate(orderHourInfo,orderHourItem,2); 
                            orderHourItem.attr('data-value', orderHourInfo.id);
                            orderHourItem.attr('data-parent', orderHourInfo.order);
                            orderHourItem.attr('data-status', orderHourInfo.status);  
                            template.find('.order-hour-container').addClass('hidden');                            
                        }         
                        orderHourItem.find('.order-hour-num').text(hourRoom); 
                    }                
                    if(orderInfo == undefined && orderHourInfo== undefined){
                        if(window.roomservice[priceKey] == '1'){
                            template.attr('title', lang('maintain.tip')); 
                        }else{
                            template.attr('title', room.name + ', ' + roomType.name + ', ' + window.symbols + roomType.price); 
                        }                        
                    }else if(orderInfo == undefined && orderHourInfo !== undefined){
                        if(window.roomservice[priceKey] == '1'){
                            template.attr('title', lang('maintain.tip')); 
                        }else{
                            template.find('.order-hour-box-other').removeClass('hidden').attr('title', room.name + ', ' + roomType.name + ', ' + window.symbols + roomType.price);
                        }
                    }
                    if (calendarHashSkipRender[currentDateFormat][roomId] === 1) {
                        return true;
                    }
                    renderHtml += template.prop('outerHTML');
                });
                // 房间类型剩余量单元
                if (typeDateCount[roomTypeId][currentDateFormat] === 0) {
                    typeDateCount[roomTypeId][currentDateFormat] = lang('fullHouse');
                }
                renderHtml += '<td class="roomTypeItemCount hidden" data-type-value="' + roomTypeId + '"><div>' + typeDateCount[roomTypeId][currentDateFormat] + '</div></td>';
            });
            renderHtml += '</tr>';
            dateIndex++;
        };
        renderHtml += '<tr class="table-tr-hidden">'
        // 房间类型单元
        $.each(window.roomTypeData, function(roomTypeId, roomType) {
            // 房间单元
            for (var i = 0; i < roomType.rooms.length; i++) {
                renderHtml += '<td data-type-value="' + roomTypeId + '"></td>';
            }
            renderHtml += '<td class="roomTypeItemCount hidden" data-type-value="' + roomTypeId + '"></td>';
        });
        renderHtml += '</tr>';
        $('#orderListBody').append(renderHtml);
//      $('#orderListBody .order-item').each(function(){
//          var tdDiv = $(this);
//          tdDiv.height(tdDiv.parent().innerHeight());
//      });
        $('#calendar .calendar-day').each(function() {
            var calendarItem = $(this);
            var dateValue = calendarItem.data('value');
            if (Object.keys(window.roomItemType).length === 0) {
                calendarItem.find('.calendar-day-count').html('');
            } else if (dateRoomAvaliable[dateValue] === 0) {
                calendarItem.find('.calendar-day-count').html(lang('fullHouse'));
            } else {
                calendarItem.find('.calendar-day-count span').html(dateRoomAvaliable[dateValue]);
            }
        });
        $('.order-item-td').removeClass('highlight');
        $('.order-item-td[data-value="' + window.hightlightRoom + '"]').addClass('highlight');
        $('.order-item-td[data-date="' + window.hightlightDate + '"]').addClass('highlight');
    });
    $('#orderListBody').on('mouseenter','.order-hour',function(){
        if($(this).data('original-title') == ''){
            $(this).next('.order-hour-container').removeClass('hidden');
        }
    }).on('mouseleave','.order-hour-box',function(){
        $(this).find('.order-hour-container').addClass('hidden');
    });    
    $('#orderListBody').on('mouseenter','.order-item.checkout,.order-item-container',function(){
        $(this).closest('.td-position').find('.order-item-container').removeClass('hidden');
    }).on('mouseleave','.order-item.checkout,.order-item-container',function(){
        $(this).closest('.td-position').find('.order-item-container').addClass('hidden');
    });
    var gettooltipTemplate = function(orderInfo,obj,type){
        // 订单的tooltip
        var templateTipOriginal = $('#templateOrderItemTip');
        tooltipTemplate = $(templateTipOriginal.clone().html());
        tooltipTemplate.find('.order-customer').html(orderInfo.name);
        if(orderInfo.mobile){
            tooltipTemplate.find('.order-mobile').html('+'+orderInfo.areaCode+'&nbsp;'+orderInfo.mobile);
        }
        tooltipTemplate.find('.order-channel').html(orderInfo.channel);
        tooltipTemplate.find('.order-status').html(orderInfo.status);
        if(type == 0){
            tooltipTemplate.find('.gettooltip-night').removeClass('hidden');
            tooltipTemplate.find('.order-start').html(orderInfo.start);
            tooltipTemplate.find('.order-end').html(orderInfo.end);
            tooltipTemplate.find('.gettooltip-night .order-night').html(orderInfo.night);
        }else if(type == 1){
            tooltipTemplate.find('.gettooltip-hour').removeClass('hidden');
            tooltipTemplate.find('.order-start').html(orderInfo.starttime);
            tooltipTemplate.find('.gettooltip-hour .order-night').html(orderInfo.hour);
        }else if(type == 3){
            tooltipTemplate.find('.gettooltip-long').removeClass('hidden');
            tooltipTemplate.find('.order-start').html(orderInfo.start);
            tooltipTemplate.find('.order-end').html(orderInfo.end);
            tooltipTemplate.find('.gettooltip-long .order-long').html(orderInfo.night);
        }else{
            tooltipTemplate.find('.gettooltip-hour').removeClass('hidden');
            tooltipTemplate.find('.order-start').html(orderInfo.starttime);
            tooltipTemplate.find('.gettooltip-hour .order-night').html(orderInfo.hour);            
        }
        tooltipTemplate.find('.order-room').html(orderInfo.roomname);
        tooltipTemplate.find('.order-price').html(orderInfo.price);
        tooltipTemplate.find('.order-receive').html(orderInfo.receipt);
        tooltipTemplate.find('.order-deposit').html(orderInfo.deposit);
        tooltipTemplate.find('.order-remark').html(orderInfo.remark);
        if(orderInfo.refundDeposit != '' && orderInfo.refundDeposit != undefined ){
            tooltipTemplate.find('.order-refund-deposit').html(orderInfo.refundDeposit).closest('.payParent').removeClass('hidden');
        }else{
            tooltipTemplate.find('.order-refund-deposit').closest('.payParent').addClass('hidden');
        }
        if(orderInfo.refundPrice != '' && orderInfo.refundPrice != undefined){
            tooltipTemplate.find('.order-refund-receive').html(orderInfo.refundPrice).closest('.payParent').removeClass('hidden');
        }else{
            tooltipTemplate.find('.order-refund-receive').closest('.payParent').addClass('hidden');
        }
        if (orderInfo.refunding == 1) {
            tooltipTemplate.find('.order-refund').removeClass('hidden');
        }
        if(type == 0){
            obj.attr('title', tooltipTemplate.prop('outerHTML'));  
        }else if(type == 1){
            tooltipTemplate.attr('data-value', orderInfo.id);
            tooltipTemplate.attr('data-parent', orderInfo.order);
            tooltipTemplate.attr('data-status', orderInfo.status);
            obj.append(tooltipTemplate.prop('outerHTML'));
        }else{
            obj.attr('title', tooltipTemplate.prop('outerHTML'));
        }      
    }    
    var refreshSelectedDate = function(selectedDate) {
        var year = selectedDate.customFormat('yyyy');
        var start = selectedDate.customFormat('MM/dd');
        var end = selectedDate.customDays(30).customFormat('MM/dd');
        datePicker.find('.start').html(start);
        datePicker.find('.end').html(end);
        datePicker.find('.year').html(year);
        window.startDate = selectedDate.customFormat();
        datePicker.data('start', window.startDate);
        refreshCalendar(selectedDate);
    };
    var weekday = [
        lang('week.7'),
        lang('week.1'),
        lang('week.2'),
        lang('week.3'),
        lang('week.4'),
        lang('week.5'),
        lang('week.6')
    ];
    var triggerRefresh = function(){
        if(window.getDataStatus==2){
            $('#doc').trigger('refresh.meizhu');
        };
    };
    var getOrderList = function(startDate){
        showMainLoading();
        // 请求该段日期的订单数据
        var param = {};
        param.hotel = window.currentHotel;
        param.start = startDate.customFormat();
        param.end = startDate.customDays(30).customFormat();
        ajaxRequest('/Home/Order/getOrderList', param, 'post', function(data) {
            window.orderList = data.data;
            hideMainLoading();
            window.getDataStatus++;
            triggerRefresh();
        }, function(error) {
            hideMainLoading();
        });
    };
    var getPriceData = function(startDate){
        var timestamp = startDate.getTime() + 3*86400000;
        var submitDate = new Date(timestamp);
        var submitDateMonth = submitDate.getMonth()+1;
        var submitDateDay = submitDate.getDate();
        var submitDateFormat = submitDate.getFullYear()+(submitDateMonth<10?'-0':'-')+submitDateMonth+(submitDateDay<10?'-0':'-')+submitDateDay;
        var param = {};
        param.hotel = window.currentHotel;
        param.date = submitDateFormat;
        ajaxRequest('/Home/Room/getPriceByHotelId', param, 'post', function(result){
            var priceData = new Array();
            var hourData = new Array();
            var longData = new Array();
            var payData = new Array();
            var serviceData = new Array();
            for(var i = 0; i < result.data.length; i++){
                var room = result.data[i];
                var hour = result.data[i];
                for(var j = 0; j < room.prices.length; j++){
                    var price = room.prices[j];
                    priceData[room.room_id + '_' + price.timestamp] = price.price;
                    serviceData[room.room_id + '_' + price.timestamp] = price.isService;
                    if(hour.hourprice.length>0){
                        var hourArr = [];
                        var priceArr = [];
                        for(var k = 0; k < hour.hourprice.length; k++){
                            hourArr.push(hour.hourprice[k].hour);
                            priceArr.push(hour.hourprice[k].price);
                            hourData[room.room_id + '_' + price.timestamp] = hourArr; 
                            payData[room.room_id + '_' + price.timestamp] = priceArr; 
                        }
                    }        
                    if(parseFloat(hour.longprice)>0){
                        longData[room.room_id + '_' + price.timestamp] = hour.longprice;
                    }                         
                }
            }
            window.roomPriceDate = submitDateFormat;
            window.roomPrices = priceData;
            window.hourprice = hourData;
            window.hourpay = payData;
            window.longprice = longData;
            window.roomservice = serviceData;
            window.getDataStatus++;
            triggerRefresh();
        });
    };
    var refreshCalendar = function(startDate) {
        window.getDataStatus = 0;
        getOrderList(startDate);
        getPriceData(startDate);
        // 计算节假日填充calendar
        var calendarItems = '';
        for (var i = 0; i < 31; i++) {
            calendarItems += createCalendarItem(startDate.customDays(i));
        }
        calendarItems += '<tr class="table-tr-hidden"><td></td></tr>';
        $('#calendar').html(calendarItems);
    };
    var templateCalendarDay = $('#templateCalendarDay');
    var createCalendarItem = function(date) {
        var template = $(templateCalendarDay.clone().html());
        var dayText = '';
        if (date.customFormat() === today.customFormat()) {
            dayText = lang('today');
            template.find('td').addClass('today');
        } else {
            dayText = date.customFormat('M/d');
        }
        template.find('td').attr('data-value', date.customFormat());
        template.find('.day-text').html(dayText);
        var weekText = getLunarFestivalOrTerm(date);
        if ($.inArray(weekText, weekday) === -1 || weekText == lang('week.7') || weekText == lang('week.6')) {
            template.find('td').addClass('has-festival');
        }
        template.find('.week-text').html(weekText);
        return template.prop('outerHTML');
    };
    /**
     * 获取节假日或二十四节气，其余情况获取周几
     */
    var getLunarFestivalOrTerm = function(date) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var info = LunarCalendar.solarToLunar(year, month, day);
        if (info.lunarFestival !== undefined) {
            return info.lunarFestival;
        }
        if (info.solarFestival !== undefined) {
            return info.solarFestival;
        }
        return weekday[date.getDay()];
    };
    var showRoomTypeCount = function(typeValue) {
        var roomTypeItemCount = $('.roomTypeItemCount[data-type-value="' + typeValue + '"]');
        roomTypeItemCount.removeClass('hidden');
        var roomTypeTr = $('.roomTypeTr[data-type-value="' + typeValue + '"]');
        roomTypeTr.removeClass('hidden');
        var orderItemTd = $('.order-item-td[data-type-value="' + typeValue + '"]');
        orderItemTd.addClass('hidden');
        var roomTypeItemRoom = $('.roomTypeItemRoom[data-type-value="' + typeValue + '"]');
        roomTypeItemRoom.addClass('hidden');
        var roomTypeItem = $('.roomTypeItem[data-type-value="' + typeValue + '"]');
        roomTypeItem.addClass('hidden');
        var bottomHiddenTypeTd = $('.table-tr-hidden td[data-type-value="' + typeValue + '"]');
        bottomHiddenTypeTd.addClass('hidden');

    };
    var hideRoomTypeCount = function(typeValue) {
        var bottomHiddenTypeTd = $('.table-tr-hidden td[data-type-value="' + typeValue + '"]');
        bottomHiddenTypeTd.removeClass('hidden');
        var roomTypeItemCount = $('.roomTypeItemCount[data-type-value="' + typeValue + '"]');
        roomTypeItemCount.addClass('hidden');
        var roomTypeTr = $('.roomTypeTr[data-type-value="' + typeValue + '"]');
        roomTypeTr.addClass('hidden');
        var orderItemTd = $('.order-item-td[data-type-value="' + typeValue + '"]');
        orderItemTd.removeClass('hidden');
        var roomTypeItemRoom = $('.roomTypeItemRoom[data-type-value="' + typeValue + '"]');
        roomTypeItemRoom.removeClass('hidden');
        var roomTypeItem = $('.roomTypeItem[data-type-value="' + typeValue + '"]');
        roomTypeItem.removeClass('hidden');
    };
    // 显示房间类型剩余量
    $('.roomTypeItemCountTrigger').on('click', function(e) {
        var typeValue = $(this).data('type-value');
        showRoomTypeCount(typeValue);
    });
    // 隐藏房间类型剩余量
    $('.roomTypeItemCountHiddenTrigger').on('click', function(e) {
        var typeValue = $(this).data('type-value');
        hideRoomTypeCount(typeValue);
    });
    window.hightlightDate = today.customFormat();
    window.hightlightRoom = '0';
    // 点击日历高亮该天的可操作td
    $('#calendar').on('click', '.calendar-day', function(e) {
        var calendarItem = $(this);
        window.hightlightDate = calendarItem.data('value');
        if (calendarItem.hasClass('highlight')) {
            calendarItem.removeClass('highlight');
            $('.order-item-td[data-date="' + window.hightlightDate + '"]').removeClass('highlight');
            $('.order-item-td[data-value="' + window.hightlightRoom + '"]').addClass('highlight');
            window.hightlightDate = '0';
        } else {
            calendarItem.addClass('highlight').parent().siblings().children().removeClass('highlight');
            $('.order-item-td[data-date!="' + window.hightlightDate + '"]').removeClass('highlight');
            $('.order-item-td[data-date="' + window.hightlightDate + '"]').addClass('highlight');
            $('.order-item-td[data-value="' + window.hightlightRoom + '"]').addClass('highlight');
        }
    });
    // 点击房间高亮该房间的可操作td
    $('.roomItem').on('click', function(e) {
        var roomItem = $(this);
        window.hightlightRoom = roomItem.data('room');
        if (roomItem.hasClass('highlight')) {
            $('.roomItem').removeClass('highlight');
            $('.order-item-td[data-value="' + window.hightlightRoom + '"]').removeClass('highlight');
            $('.order-item-td[data-date="' + window.hightlightDate + '"]').addClass('highlight');
            window.hightlightRoom = '0';
        } else {
            $('.roomItem').removeClass('highlight');
            roomItem.addClass('highlight');
            $('.order-item-td[data-value!="' + window.hightlightRoom + '"]').removeClass('highlight');
            $('.order-item-td[data-value="' + window.hightlightRoom + '"]').addClass('highlight');
            $('.order-item-td[data-date="' + window.hightlightDate + '"]').addClass('highlight');
        }
    });
    refreshCalendar(getDate(window.startDate));
    $('#pushCenter').on('push',function(){
        refreshCalendar(getDate(window.startDate));
    });
    $("#editOrderConfirm").on('afterCommit', function() {
        refreshCalendar(getDate(window.startDate));
    });
    $("#checkInConfirm").on('afterBlrzCommit', function() {
        refreshCalendar(getDate(window.startDate));
    });  
    // 可移动模态框
    interact('.modal-header').ignoreFrom('input, textarea').draggable({
        restrict: {
            restriction: 'body',
            endOnly: true
        },
        autoScroll: false,
        onmove: function dragMoveListener(event) {
            var target = event.target,
                x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
                y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
            var targetMovable = $(target).parent();
            var translate = 'translate(' + x + 'px, ' + y + 'px)';
            targetMovable.css('-webkit-transform', translate);
            targetMovable.css('transform', translate);
            target.setAttribute('data-x', x);
            target.setAttribute('data-y', y);
        },
        onend: function(event) {
            var target = event.target,
                x = parseFloat(target.getAttribute('data-x')) || 0,
                y = parseFloat(target.getAttribute('data-y')) || 0;
            var targetMovable = $(target).parent(),
                offsetX = parseInt(targetMovable.css('left')) || 0,
                offsetY = parseInt(targetMovable.css('top')) || 0;
            target.setAttribute('data-x', 0);
            target.setAttribute('data-y', 0);
            targetMovable.css('-webkit-transform', '');
            targetMovable.css('transform', '');
            targetMovable.css('left', offsetX + x + 'px');
            targetMovable.css('top', offsetY + y + 'px');
        }
    });
    
    // 房态显示的时候lazyload
    $('#viewstyleModal').on('show.bs.modal', function(e){
        $('#viewstyleModal .viewstylePreview').lazyload({
            failure_limit : 10,
            effect: 'fadeIn'
        });
    });
    
    //维修房
    var maintainContainer = $('#maintains-container');
    $('.roomItem').mouseenter(function(e){
        e.stopPropagation();
        var $me = $(this);
        window.obj = $me;
        window.isservice = false;
        var offset = $me.offset(); 
        maintainContainer.css('left',offset.left+30);
        var room = $me.data('room');
        var roomType = $me.closest('td').attr('data-type-value');
        var docText = $me.data('status') === 0 ? lang('click.dirty') : lang('click.clean');
        var isServiceText = $me.data('isservice') === 0 ? lang('maintain.click') : lang('click.clean');
        maintainContainer.find('.dirty-content').text(docText);
        maintainContainer.find('.maintain-content').text(isServiceText);
        maintainContainer.find('.dirty-list').data('room',room);
        maintainContainer.find('.dirty-list').data('status',$me.data('status'));
        maintainContainer.find('.maintain-list').data('room',room);
        maintainContainer.find('.maintain-list').data('isservice',$me.data('isservice'));
        maintainContainer.find('.maintain-list').data('roomtype',roomType);
        $('#submitRepair').data('room',room);
        $('#submitRepair').data('roomtype',roomType);
        maintainContainer.removeClass('hidden');
    }).mouseleave(function(e){
        maintainContainer.addClass('hidden');
    });
    maintainContainer.mouseenter(function(e){
        maintainContainer.removeClass('hidden');
    }).mouseleave(function(e){
        maintainContainer.addClass('hidden');
    });    
    $('#submitRepair').on('click', function(e) {
        var submitBtn = $(this);
        var param = {
                hotel: window.currentHotel,
                roomId: submitBtn.data('room'),
                roomTypeId:submitBtn.data('roomtype'),
                status: 1,
                startDate:$('#repairStartTime').val(),
                endDate:$('#repairEndTime').val()
        };
        ajaxRequest('/Home/Room/setService', param, 'post',function(data){
            formInlineTip(submitBtn, lang('successfullySave'));
            $('.roomItem[data-room=' +submitBtn.data('room') + ']').data('isservice',1);
            maintainContainer.find('.maintain-content').text(lang('click.clean'));
            refreshCalendar(getDate(window.startDate));
            $('#repairModal').modal('hide');
        } , function(error) {
            if (error.responseJSON === undefined) {
                formInlineTip(submitBtn, lang('tip.server'));
            } else {
                formInlineTip(submitBtn, error.responseJSON.info);
            }
        }, submitBtn);
    });    
    // 设置维修房干净房接口
    maintainContainer.on('click','.maintain-list',function(e){
        e.stopPropagation();
        var $me = $(this);
        var isservice = $me.data('isservice');
        if(window.isservice){
            isservice = 0;
        }
        if(isservice == 1){
            var param = {
                    hotel: window.currentHotel,
                    roomId: $me.data('room'),
                    roomTypeId:$me.data('roomtype'),
                    status: 0
            };
            ajaxRequest('/Home/Room/setService', param, 'post', function (data) {
                $('.roomItem[data-room=' +$me.data('room') + ']').data('isservice',0);
                maintainContainer.find('.maintain-content').text(lang('maintain.click'));
                refreshCalendar(getDate(window.startDate));
                window.isservice = true;
            }, function (error) {
                if (error.responseJSON !== undefined) {
                    modalAlert(error.responseJSON.info);
                }
            }, $me);             
        }else{
            var today = $('#doc').data('today');
            $('#repairStartTime').val(today);
            $('#repairEndTime').val(today);
            $('#repairModal .form-group').removeClass('has-error');
            $('#repairModal').modal('show');
        }
    });      
});
